import re

from django.shortcuts import render

# Create your views here.
from rest_framework import serializers
from rest_framework import status
from rest_framework.generics import RetrieveAPIView,GenericAPIView, ListAPIView, CreateAPIView
from rest_framework.pagination import PageNumberPagination
from rest_framework.generics import RetrieveAPIView,GenericAPIView,ListAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response

from rest_framework.views import APIView

from questions.models import Questions, Answer, Label
from questions.serializers import QuestionSerializer,AnswerListSerializer,AnswerCreateSerializer, HotLabelSerializer, \
    CreateQuestions
from questions.models import Questions, Answer
from questions.serializers import QuestionInfo, NewObserver
from users.models import User


from questions.models import Questions, Answer,QuestionClick,UserAnswer, Label, UserLabel
from questions.serializers import QuestionSerializer,AnswerListSerializer,AnswerCreateSerializer, \
    SimilarityQusetionsSerializer,LabelSerializer,LabelRetrieveSerializer


class QuestionRetrieveAPIView(RetrieveAPIView):
    serializer_class = QuestionSerializer
    queryset = Questions.objects.all()

    def get(self,request,pk):
        question = self.get_queryset().get(id=pk)
        question.pageviews += 1
        question.save()
        return self.retrieve(request,pk)



class AnswerListAPIView(APIView):
    def perform_authentication(self, request):
        """
        重写父类的用户验证方法，不在进入视图前就检查JWT
        """
        pass

    def get(self,request,pk):
        queryset = Answer.objects.filter(question_id=pk).order_by('create_time')

        s = AnswerListSerializer(queryset,many=True)

        return Response(s.data)


    def post(self,request,pk):
        try:
            user = request.user
        except Exception:
            # 验证失败，用户未登录
            return Response(data={'error':'发布评论失败，用户未登录'},status=status.HTTP_400_BAD_REQUEST)

        if user is not None and user.is_authenticated:
            user_id = user.id
            question_id = pk

            data = {
                "user":user_id,
                "question":question_id,
                "content":request.data.get('content'),
                "parent":request.data.get('parent')
            }
            s = AnswerCreateSerializer(data=data)
            s.is_valid()
            s.save()
            question = Questions.objects.get(id=question_id)
            question.answer_count += 1
            question.save()
            return Response(data={'msg':'OK'},status=status.HTTP_201_CREATED)





class ClickLikeAPIView(APIView):
    permission_classes = [IsAuthenticated]

    def post(self,request):
        user = request.user
        action = request.data.get('action')
        click_obj = self.get_queryset()
        click_id = self.request.data.get('click_id')
        click_count = 1
        is_like = True
        if click_obj.filter(user=user):
            return Response(data={'msg':'用户对同一问题或评论仅可点赞或踩一次'},status=status.HTTP_400_BAD_REQUEST)

        if action == 'boo':
            click_count = -1
            is_like = False
        if self.request.data.get('click_type') == 'question':
            question_like_obj = QuestionClick(question_id=click_id,user=user,is_like=is_like)
            question_like_obj.save()
            question = Questions.objects.get(id=click_id)
            question.clicks += click_count
            question.save()
            return Response(data={'msg':'0K'},status=status.HTTP_200_OK)

        else:

            answer_like_obj = UserAnswer(answer_id=click_id,user=user,is_like=is_like)
            answer_like_obj.save()
            answer = Answer.objects.get(id=click_id)
            answer.clicks += click_count
            answer.save()
            return Response(data={'msg': '0K'}, status=status.HTTP_200_OK)




    def get_queryset(self):
        click_id = self.request.data.get('click_id')
        if self.request.data.get('click_type') == 'question':
            return QuestionClick.objects.filter(question=click_id)
        else:
            return UserAnswer.objects.filter(answer=click_id)


class SimilarityQusetionsAPIView(APIView):
    def get(self,request,pk):

        qu = Questions.objects.get(id=pk)
        lab = qu.labels.first()

        qu_obj_list = Questions.objects.filter(labels=lab).exclude(id=pk)[0:5]
        if not qu_obj_list:
            return Response(data=[])
        quest_data = SimilarityQusetionsSerializer(qu_obj_list,many=True).data
        for qu_obj in quest_data:
            is_solve = '未解决'
            if qu_obj['answer_count'] > 0:
                is_solve = '已解决'

            qu_obj['is_solve'] = is_solve

        return Response(data=quest_data,status=status.HTTP_200_OK)


class LabelListAPIView(ListAPIView):
    serializer_class = LabelSerializer
    queryset = Label.objects.all().order_by('-attention')

    def perform_authentication(self, request):
        """
        重写父类的用户验证方法，不在进入视图前就检查JWT
        """
        pass


    def get(self, request, *args, **kwargs):
        response = self.list(request)
        user_attention_label_list = []

        try:
            user = self.request.user
        except:
            user = None


        if user is not None and user.is_authenticated:

            user_attention_set = UserLabel.objects.filter(user=user)
            for user_attention in user_attention_set:
                user_attention_label_list.append(user_attention.label_id)
            for label_dict in response.data:

                    if label_dict['id']  in user_attention_label_list:
                        label_dict['is_attention'] = True

                    else:
                        label_dict['is_attention'] = False

            return response

        else:
            for label_dict in response.data:
                label_dict['is_attention'] = False

            return response



class AttentionLabelAPIView(APIView):
    permission_classes = [IsAuthenticated]
    def post(self,request):
        user = request.user
        label_id = request.data.get('label_id')
        if UserLabel.objects.filter(user=user,label=label_id):
            return Response(data={'msg':'用户已注册'},status=status.HTTP_401_UNAUTHORIZED)
        UserLabel.objects.create(user=user,label_id=label_id)
        label = Label.objects.get(id=label_id)
        label.attention += 1
        label.save()
        return Response(data={'msg':'ok'},status = status.HTTP_201_CREATED)

class LabelRetrieveAPIView(RetrieveAPIView):
    serializer_class =LabelRetrieveSerializer
    queryset = Label.objects.all()

# class LabelQuestionsAPIView(ListAPIView):
#     serializer_class = QuestionSerializer

    # def get_queryset(self):
    #     label_id = self.request.query_params.get('label_id')
    #     order = self.request.query_params.get('order')
    #
    #     if order=='1':
    #         return Questions.objects.filter(labels=label_id).order_by("create_time")
    #     else:
    #         return Questions.objects.filter(labels=label_id).order_by("-clicks")
    #


class LabelQuestionsAPIView(GenericAPIView):

    def get(self, request):
        label_id = request.query_params['label_id']
        order_id = request.query_params['order']
        if order_id =='1':
            try:
                q1 = Questions.objects.filter(labels=label_id).order_by("create_time")
            except Exception:
                raise Questions.DoesNotExist
        else:
            try:
                q1 = Questions.objects.filter(labels=label_id).order_by("-clicks")
            except Exception:
                raise Questions.DoesNotExist

        serializer = QuestionSerializer(q1,many=True)
        question_list = serializer.data

        for question in question_list:
            #查询当前新闻的最新评论
            try:
                observer = Answer.objects.filter(question_id=question['id']).order_by('-create_time').only('user_id',
                                                                                                           'create_time')[
                    0]
                question['new_observer'] = NewObserver(observer).data
            except Exception:
                pass

        return Response(question_list)




#####################################

class LargeResultsSetPagination(PageNumberPagination):
    """
    分页
    """
    #每页数量
    page_size = 10
    page_size_query_param = 'page_size'
    max_page_size = 10000



class Question(GenericAPIView):
    """
    获取问答主页列表数据
    """


    def get(self,request):

        category_id = request.query_params['category_id']
        if category_id == '1':
            #获取查询集
            try:
                q1 = Questions.objects.exclude(answer_count=0).order_by('-update_time')
            except Exception:
                raise Questions.DoesNotExist('问题不存在')
        elif category_id == '2':
            try:
                q1 = Questions.objects.all().order_by('-answer_count')

            except Exception:
                raise Questions.DoesNotExist('问题不存在')
        else:
            try:
                q1 = Questions.objects.filter(answer_count=0).order_by('create_time')
            except Exception:
                pass
        #进行序列化
        serializer = QuestionInfo(q1, many=True)
        question_list = serializer.data

        #通过遍历每一个对象，给对象中添加额外数据
        for question in question_list:

            #查询当前新闻最新评论者和时间
            try:
                observer = Answer.objects.filter(question_id=question['id']).order_by('-create_time').only('user_id','create_time')[0]
                question['new_observer'] = NewObserver(observer).data
            except Exception:
                pass


        return Response(question_list)


class HotLabel(ListAPIView):

    """
    返回热门标签
    """
    serializer_class = HotLabelSerializer

    def get_queryset(self):
        return Label.objects.all().order_by('-attention')[0:5]



class CreateQuestion(CreateAPIView):
    """
    创建问题
    """
    permissoin_classes = [IsAuthenticated]

    serializer_class = CreateQuestions

    def post(self, request, *args, **kwargs):
        author_name = request.user.id
        request.data['author_name']=author_name
        label_name = re.split(",|;", request.data['labels'])
        label_list=[]
        for i in label_name:
            i.strip().title()
            try:
                label = Label.objects.get(name=i)
            except Label.DoesNotExist:
                raise serializers.ValidationError('标签不存在')

            except Exception as e:
                raise serializers.ValidationError('数据库查询错误%s'% e)

            label_list.append(label.id)
        request.data['labels']=label_list


        return self.create(request)

    # def post(self, request):
    #     question_data = request.data
    #     print(question_data)
    #     data = {
    #         'title': question_data['title'],
    #         'author_name': request.user.id,
    #         'content': question_data['qa_content'],
    #         'labels': question_data['label'],
    #     }
    #      = re.split(',|;', data["labels"])
    #
    #
    #     serializer = CreateQuestions(data=data)
    #     serializer.is_valid(raise_exception=True)
    #     serializer.save()
    #
    #     return Response(data={'message': 'ok'})



